package com.p2p.backend.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.p2p.backend.controller.form.RoleForm;
import com.p2p.backend.dao.RoleDao;
import com.p2p.backend.dao.RolePrivilegeDao;
import com.p2p.backend.dao.UserRoleDao;
import com.p2p.backend.service.RoleService;

/**
 * leiwen@yiqihao.com
 */
@Service("roleService")
public class RoleServiceImpl implements RoleService {

	@Resource
	private RoleDao roleDao;
	
	@Resource
	private UserRoleDao userRoleDao;
	
	@Resource
	private RolePrivilegeDao rolePrivilegeDao;

	@Override
	@Transactional
	public void add(RoleForm role) {
		roleDao.add(role);
		addPrivileges(role);
	}

	private void addPrivileges(RoleForm role) {
		Integer roleId = role.getId();
		String[] privileges = role.getPrivilegeArray();
		if (privileges != null) {
			for (String acl : privileges) {
				if (StringUtils.isNotBlank(acl)) {
					Map<String, Object> params = new HashMap<String, Object>();
					params.put("role_id", roleId);
					params.put("privilege_acl", acl);
					rolePrivilegeDao.add(params);
				}
			}
		}
	}

	@Override
	@Transactional
	public void update(RoleForm role) {
		roleDao.update(role);
		Integer roleId = role.getId();
		// 先删除已有的权限
		rolePrivilegeDao.deleteByRole(roleId);
		addPrivileges(role);
	}

	@Override
	public List<Map<String, Object>> listAll() {
		return roleDao.listAll();
	}

	@Override
	public Map<String, Object> get(Integer id) {
		return roleDao.get(id);
	}

	@Override
	public Map<String, Object> getDetail(Integer id) {
		return roleDao.get(id);
	}

	@Override
	@Transactional
	public boolean delete(Integer id) {
		boolean succeed=false;
		List<Map<String, Object>> list = userRoleDao.getByRole(id);
		if (list == null || list.size()==0) {
			roleDao.delete(id);
			succeed=true;
		} 
		return succeed;
	}

}
